import pygame
import sys

# 定义常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
TOTAL_WIDTH = SCREEN_WIDTH

# 定义颜色
BG_COLOR = (15, 15, 30)  # 使用俄罗斯方块的深蓝色背景
TEXT_COLOR = (255, 255, 255)
MENU_BG_COLOR = (25, 25, 45)  # 使用俄罗斯方块的侧边栏颜色
MENU_HIGHLIGHT_COLOR = (255, 215, 0)  # 使用俄罗斯方块的金色强调色
MENU_NORMAL_COLOR = (128, 128, 128)
BUTTON_BG_COLOR = (40, 40, 60)
BUTTON_HOVER_COLOR = (60, 60, 80)
BUTTON_BORDER_COLOR = (100, 100, 120)
NEON_BLUE = (0, 255, 255)  # 使用俄罗斯方块的霓虹蓝
WHITE = (255, 255, 255)

# 全局变量
menu_buttons = []  # 存储菜单按钮

def draw_gradient_rect(surface, color1, color2, rect, vertical=True):
    """绘制渐变矩形"""
    if vertical:
        for y in range(rect.height):
            blend = y / rect.height
            r = int(color1[0] * (1 - blend) + color2[0] * blend)
            g = int(color1[1] * (1 - blend) + color2[1] * blend)
            b = int(color1[2] * (1 - blend) + color2[2] * blend)
            pygame.draw.line(surface, (r, g, b),
                             (rect.x, rect.y + y), (rect.x + rect.width, rect.y + y))
    else:
        for x in range(rect.width):
            blend = x / rect.width
            r = int(color1[0] * (1 - blend) + color2[0] * blend)
            g = int(color1[1] * (1 - blend) + color2[1] * blend)
            b = int(color1[2] * (1 - blend) + color2[2] * blend)
            pygame.draw.line(surface, (r, g, b),
                             (rect.x + x, rect.y), (rect.x + x, rect.y + rect.height))

def draw_rounded_rect(surface, color, rect, radius=12, width=0):
    """绘制圆角矩形"""
    pygame.draw.rect(surface, color, rect, width=width, border_radius=radius)

def draw_glowing_rect(surface, color, rect, glow_size=2):
    """绘制发光效果的矩形"""
    # 绘制外层发光
    for i in range(glow_size, 0, -1):
        glow_color = tuple(min(255, c + 20 * i) for c in color)
        glow_rect = pygame.Rect(rect.x - i, rect.y - i, rect.width + 2 * i, rect.height + 2 * i)
        pygame.draw.rect(surface, glow_color, glow_rect, border_radius=8)

    # 绘制主体
    pygame.draw.rect(surface, color, rect, border_radius=6)

def draw_tetris_logo(screen, x, y, size=40):
    """绘制俄罗斯方块风格的Logo"""
    # 绘制几个彩色方块作为Logo
    colors = [
        (0, 255, 255),  # 青色
        (0, 100, 255),  # 蓝色
        (255, 165, 0),  # 橙色
        (255, 255, 0),  # 黄色
        (0, 255, 100),  # 绿色
        (160, 32, 240),  # 紫色
        (255, 50, 50),  # 红色
    ]
    
    # 绘制一个简单的"T"形状
    block_size = size // 4
    positions = [
        (0, 0), (1, 0), (2, 0),  # 顶部横线
        (1, 1), (1, 2), (1, 3)   # 中间竖线
    ]
    
    for i, (dx, dy) in enumerate(positions):
        color = colors[i % len(colors)]
        rect = pygame.Rect(x + dx * block_size, y + dy * block_size, block_size, block_size)
        draw_glowing_rect(screen, color, rect, glow_size=1)

def draw_menu(screen, total_width, screen_height):
    """绘制主菜单界面 - 供主游戏调用"""
    # 在函数内部加载字体，避免在模块导入时就初始化
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 48, bold=True)
    subtitle_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24)
    
    # 创建按钮列表
    menu_buttons = []
    
    # 绘制背景渐变
    draw_gradient_rect(screen, BG_COLOR, (0, 0, 0), 
                       pygame.Rect(0, 0, total_width, screen_height))
    
    # 绘制装饰性网格（俄罗斯方块风格）
    for x in range(0, total_width, 60):
        pygame.draw.line(screen, (25, 25, 45), (x, 0), (x, screen_height), 1)
    for y in range(0, screen_height, 60):
        pygame.draw.line(screen, (25, 25, 45), (0, y), (total_width, y), 1)
    
    # 计算布局参数
    logo_size = 120
    logo_y = 80  # 固定Logo位置在顶部
    logo_x = total_width // 2 - logo_size // 2
    
    # 绘制Logo
    draw_tetris_logo(screen, logo_x, logo_y, logo_size)
    
    # 绘制标题（在Logo下方）
    title_text = title_font.render("俄罗斯方块", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(total_width // 2, logo_y + logo_size + 40))
    
    # 绘制发光效果
    for i in range(3):
        glow_color = tuple(min(255, c + 30 - i * 10) for c in MENU_HIGHLIGHT_COLOR)
        glow_text = title_font.render("俄罗斯方块", True, glow_color)
        screen.blit(glow_text, (title_rect.x - i, title_rect.y - i))
    
    screen.blit(title_text, title_rect)
    
    # 绘制副标题（在标题下方）
    subtitle_text = subtitle_font.render("经典益智游戏", True, NEON_BLUE)
    subtitle_rect = subtitle_text.get_rect(center=(total_width // 2, title_rect.bottom + 20))
    screen.blit(subtitle_text, subtitle_rect)
    
    # 创建按钮（在副标题下方，合理分布）
    button_width = 220
    button_height = 55
    button_spacing = 20  # 按钮间距
    total_buttons_height = 3 * button_height + 2 * button_spacing
    buttons_start_y = subtitle_rect.bottom + 60  # 与副标题保持距离
    
    button_x = total_width // 2 - button_width // 2
    
    # 开始游戏按钮
    start_button = pygame.Rect(button_x, buttons_start_y, button_width, button_height)
    menu_buttons.append(("start", start_button))
    
    # 游戏规则按钮
    rules_button = pygame.Rect(button_x, buttons_start_y + button_height + button_spacing, button_width, button_height)
    menu_buttons.append(("rules", rules_button))
    
    # 退出游戏按钮
    exit_button = pygame.Rect(button_x, buttons_start_y + 2 * (button_height + button_spacing), button_width, button_height)
    menu_buttons.append(("exit", exit_button))
    
    # 绘制按钮
    for action, button_rect in menu_buttons:
        # 根据悬停状态选择颜色
        is_hover = button_rect.collidepoint(pygame.mouse.get_pos())
        
        if is_hover:
            # 悬停状态：发光效果
            draw_glowing_rect(screen, BUTTON_HOVER_COLOR, button_rect, glow_size=3)
            text_color = MENU_HIGHLIGHT_COLOR
            border_color = NEON_BLUE
        else:
            # 普通状态：渐变背景
            draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 30, 50), button_rect)
            text_color = MENU_NORMAL_COLOR
            border_color = BUTTON_BORDER_COLOR
        
        # 绘制按钮边框
        pygame.draw.rect(screen, border_color, button_rect, 2, border_radius=8)
        
        # 绘制按钮文字
        if action == "start":
            text = "开始游戏"
        elif action == "rules":
            text = "游戏规则"
        elif action == "exit":
            text = "退出游戏"
        
        text_surface = button_font.render(text, True, text_color)
        text_rect = text_surface.get_rect(center=button_rect.center)
        screen.blit(text_surface, text_rect)
    
    # 绘制底部装饰
    bottom_y = screen_height - 60
    pygame.draw.line(screen, NEON_BLUE, (50, bottom_y), (total_width - 50, bottom_y), 2)
    
    # 绘制版本信息
    version_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 16)
    version_text = version_font.render("俄罗斯方块增强版 v1.0", True, (100, 100, 100))
    version_rect = version_text.get_rect(center=(total_width // 2, screen_height - 30))
    screen.blit(version_text, version_rect)
    
    # 移除pygame.display.flip()调用，避免在MOUSEMOTION事件中重复刷新屏幕
    # pygame.display.flip()
    return menu_buttons

def handle_menu_click(pos, buttons):
    """处理菜单点击事件 - 供主游戏调用"""
    for action, button_rect in buttons:
        if button_rect.collidepoint(pos):
            return action
    return None

def draw_exit_confirm_dialog(screen, total_width, screen_height):
    """绘制退出确认对话框"""
    # 创建半透明遮罩
    overlay = pygame.Surface((total_width, screen_height))
    overlay.set_alpha(128)
    overlay.fill((0, 0, 0))
    screen.blit(overlay, (0, 0))
    
    # 对话框尺寸和位置
    dialog_width = 400
    dialog_height = 200
    dialog_x = (total_width - dialog_width) // 2
    dialog_y = (screen_height - dialog_height) // 2
    
    # 绘制对话框背景
    dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
    draw_gradient_rect(screen, (40, 40, 60), (30, 30, 50), dialog_rect)
    pygame.draw.rect(screen, NEON_BLUE, dialog_rect, 3, border_radius=12)
    
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24, bold=True)
    content_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 18)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20)
    
    # 绘制标题
    title_text = title_font.render("确认退出", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 40))
    screen.blit(title_text, title_rect)
    
    # 绘制内容
    content_text = content_font.render("确定要退出游戏吗？", True, TEXT_COLOR)
    content_rect = content_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 80))
    screen.blit(content_text, content_rect)
    
    # 创建按钮
    button_width = 100
    button_height = 40
    button_spacing = 30
    
    # 是按钮
    yes_button = pygame.Rect(dialog_x + dialog_width // 2 - button_width - button_spacing // 2, 
                            dialog_y + dialog_height - 70, button_width, button_height)
    
    # 否按钮
    no_button = pygame.Rect(dialog_x + dialog_width // 2 + button_spacing // 2, 
                           dialog_y + dialog_height - 70, button_width, button_height)
    
    # 获取鼠标位置
    mouse_pos = pygame.mouse.get_pos()
    
    # 绘制是按钮
    is_yes_hover = yes_button.collidepoint(mouse_pos)
    if is_yes_hover:
        draw_glowing_rect(screen, (255, 80, 80), yes_button, glow_size=2)
        yes_text_color = WHITE
    else:
        draw_gradient_rect(screen, (80, 40, 40), (60, 30, 30), yes_button)
        yes_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (255, 100, 100), yes_button, 2, border_radius=8)
    yes_text = button_font.render("是", True, yes_text_color)
    yes_text_rect = yes_text.get_rect(center=yes_button.center)
    screen.blit(yes_text, yes_text_rect)
    
    # 绘制否按钮
    is_no_hover = no_button.collidepoint(mouse_pos)
    if is_no_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, no_button, glow_size=2)
        no_text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 30, 50), no_button)
        no_text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, no_button, 2, border_radius=8)
    no_text = button_font.render("否", True, no_text_color)
    no_text_rect = no_text.get_rect(center=no_button.center)
    screen.blit(no_text, no_text_rect)
    
    # 移除pygame.display.flip()调用，避免在MOUSEMOTION事件中重复刷新屏幕
    # pygame.display.flip()
    return yes_button, no_button

def draw_main_menu_exit_confirm(screen, total_width, screen_height):
    """绘制主菜单退出确认对话框"""
    # 不创建背景遮罩，让初始化菜单界面可见
    
    # 对话框尺寸和位置
    dialog_width = 400
    dialog_height = 200
    dialog_x = (total_width - dialog_width) // 2
    dialog_y = (screen_height - dialog_height) // 2
    
    # 绘制对话框背景（半透明）
    dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
    # 创建半透明的对话框背景
    dialog_surface = pygame.Surface((dialog_width, dialog_height))
    dialog_surface.set_alpha(220)  # 设置透明度
    draw_gradient_rect(dialog_surface, (40, 40, 60), (30, 30, 50), pygame.Rect(0, 0, dialog_width, dialog_height))
    screen.blit(dialog_surface, (dialog_x, dialog_y))
    pygame.draw.rect(screen, NEON_BLUE, dialog_rect, 3, border_radius=12)
    
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24, bold=True)
    content_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 18)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20)
    
    # 绘制标题
    title_text = title_font.render("确认退出", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 40))
    screen.blit(title_text, title_rect)
    
    # 绘制内容
    content_text = content_font.render("确定要退出游戏吗？", True, TEXT_COLOR)
    content_rect = content_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 80))
    screen.blit(content_text, content_rect)
    
    # 创建按钮
    button_width = 100
    button_height = 40
    button_spacing = 30
    
    # 是按钮
    yes_button = pygame.Rect(dialog_x + dialog_width // 2 - button_width - button_spacing // 2, 
                            dialog_y + dialog_height - 70, button_width, button_height)
    
    # 否按钮
    no_button = pygame.Rect(dialog_x + dialog_width // 2 + button_spacing // 2, 
                           dialog_y + dialog_height - 70, button_width, button_height)
    
    # 获取鼠标位置
    mouse_pos = pygame.mouse.get_pos()
    
    # 绘制是按钮
    is_yes_hover = yes_button.collidepoint(mouse_pos)
    if is_yes_hover:
        draw_glowing_rect(screen, (255, 80, 80), yes_button, glow_size=2)
        yes_text_color = WHITE
    else:
        draw_gradient_rect(screen, (80, 40, 40), (60, 30, 30), yes_button)
        yes_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (255, 100, 100), yes_button, 2, border_radius=8)
    yes_text = button_font.render("是", True, yes_text_color)
    yes_text_rect = yes_text.get_rect(center=yes_button.center)
    screen.blit(yes_text, yes_text_rect)
    
    # 绘制否按钮
    is_no_hover = no_button.collidepoint(mouse_pos)
    if is_no_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, no_button, glow_size=2)
        no_text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 30, 50), no_button)
        no_text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, no_button, 2, border_radius=8)
    no_text = button_font.render("否", True, no_text_color)
    no_text_rect = no_text.get_rect(center=no_button.center)
    screen.blit(no_text, no_text_rect)
    
    # 移除pygame.display.flip()调用，避免在MOUSEMOTION事件中重复刷新屏幕
    # pygame.display.flip()
    return yes_button, no_button

def draw_game_menu_exit_confirm(screen, total_width, screen_height):
    """绘制游戏内菜单退出确认对话框"""
    # 不创建背景遮罩，让游戏界面可见
    
    # 对话框尺寸和位置
    dialog_width = 400
    dialog_height = 200
    dialog_x = (total_width - dialog_width) // 2
    dialog_y = (screen_height - dialog_height) // 2
    
    # 绘制对话框背景（半透明）
    dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
    # 创建半透明的对话框背景
    dialog_surface = pygame.Surface((dialog_width, dialog_height))
    dialog_surface.set_alpha(220)  # 设置透明度
    draw_gradient_rect(dialog_surface, (40, 40, 60), (30, 30, 50), pygame.Rect(0, 0, dialog_width, dialog_height))
    screen.blit(dialog_surface, (dialog_x, dialog_y))
    pygame.draw.rect(screen, NEON_BLUE, dialog_rect, 3, border_radius=12)
    
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24, bold=True)
    content_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 18)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20)
    
    # 绘制标题
    title_text = title_font.render("确认退出", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 40))
    screen.blit(title_text, title_rect)
    
    # 绘制内容
    content_text = content_font.render("确定要退出游戏吗？", True, TEXT_COLOR)
    content_rect = content_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 80))
    screen.blit(content_text, content_rect)
    
    # 创建按钮
    button_width = 100
    button_height = 40
    button_spacing = 30
    
    # 是按钮
    yes_button = pygame.Rect(dialog_x + dialog_width // 2 - button_width - button_spacing // 2, 
                            dialog_y + dialog_height - 70, button_width, button_height)
    
    # 否按钮
    no_button = pygame.Rect(dialog_x + dialog_width // 2 + button_spacing // 2, 
                           dialog_y + dialog_height - 70, button_width, button_height)
    
    # 获取鼠标位置
    mouse_pos = pygame.mouse.get_pos()
    
    # 绘制是按钮
    is_yes_hover = yes_button.collidepoint(mouse_pos)
    if is_yes_hover:
        draw_glowing_rect(screen, (255, 80, 80), yes_button, glow_size=2)
        yes_text_color = WHITE
    else:
        draw_gradient_rect(screen, (80, 40, 40), (60, 30, 30), yes_button)
        yes_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (255, 100, 100), yes_button, 2, border_radius=8)
    yes_text = button_font.render("是", True, yes_text_color)
    yes_text_rect = yes_text.get_rect(center=yes_button.center)
    screen.blit(yes_text, yes_text_rect)
    
    # 绘制否按钮
    is_no_hover = no_button.collidepoint(mouse_pos)
    if is_no_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, no_button, glow_size=2)
        no_text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 30, 50), no_button)
        no_text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, no_button, 2, border_radius=8)
    no_text = button_font.render("否", True, no_text_color)
    no_text_rect = no_text.get_rect(center=no_button.center)
    screen.blit(no_text, no_text_rect)
    
    # 移除pygame.display.flip()调用，避免在MOUSEMOTION事件中重复刷新屏幕
    # pygame.display.flip()
    return yes_button, no_button

def draw_game_menu(screen, total_width, screen_height):
    """绘制游戏内菜单"""
    # 不创建背景遮罩，让游戏界面可见
    
    # 菜单尺寸和位置
    menu_width = 320  # 增加宽度
    menu_height = 320  # 增加高度
    menu_x = (total_width - menu_width) // 2
    menu_y = (screen_height - menu_height) // 2
    
    # 绘制菜单背景（半透明）
    menu_rect = pygame.Rect(menu_x, menu_y, menu_width, menu_height)
    # 创建半透明的菜单背景
    menu_surface = pygame.Surface((menu_width, menu_height))
    menu_surface.set_alpha(200)  # 设置透明度
    draw_gradient_rect(menu_surface, (40, 40, 60), (30, 30, 50), pygame.Rect(0, 0, menu_width, menu_height))
    screen.blit(menu_surface, (menu_x, menu_y))
    pygame.draw.rect(screen, NEON_BLUE, menu_rect, 3, border_radius=12)
    
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 32, bold=True)  # 增加标题字体大小
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24)  # 增加按钮字体大小
    
    # 绘制标题
    title_text = title_font.render("游戏菜单", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(menu_x + menu_width // 2, menu_y + 50))  # 增加标题位置
    screen.blit(title_text, title_rect)
    
    # 创建按钮
    button_width = 220  # 增加按钮宽度
    button_height = 50  # 增加按钮高度
    button_spacing = 25  # 增加按钮间距
    buttons_start_y = menu_y + 100  # 增加按钮起始位置
    
    # 继续游戏按钮
    continue_button = pygame.Rect(menu_x + (menu_width - button_width) // 2, 
                                 buttons_start_y, button_width, button_height)
    
    # 游戏说明按钮
    rules_button = pygame.Rect(menu_x + (menu_width - button_width) // 2, 
                              buttons_start_y + button_height + button_spacing, 
                              button_width, button_height)
    
    # 退出游戏按钮
    exit_button = pygame.Rect(menu_x + (menu_width - button_width) // 2, 
                             buttons_start_y + 2 * (button_height + button_spacing), 
                             button_width, button_height)
    
    # 获取鼠标位置
    mouse_pos = pygame.mouse.get_pos()
    
    # 绘制继续游戏按钮
    is_continue_hover = continue_button.collidepoint(mouse_pos)
    if is_continue_hover:
        draw_glowing_rect(screen, (60, 120, 60), continue_button, glow_size=2)
        continue_text_color = WHITE
    else:
        draw_gradient_rect(screen, (40, 80, 40), (30, 60, 30), continue_button)
        continue_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (80, 160, 80), continue_button, 2, border_radius=8)
    continue_text = button_font.render("继续游戏", True, continue_text_color)
    continue_text_rect = continue_text.get_rect(center=continue_button.center)
    screen.blit(continue_text, continue_text_rect)
    
    # 绘制游戏说明按钮
    is_rules_hover = rules_button.collidepoint(mouse_pos)
    if is_rules_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, rules_button, glow_size=2)
        rules_text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 30, 50), rules_button)
        rules_text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, rules_button, 2, border_radius=8)
    rules_text = button_font.render("游戏说明", True, rules_text_color)
    rules_text_rect = rules_text.get_rect(center=rules_button.center)
    screen.blit(rules_text, rules_text_rect)
    
    # 绘制退出游戏按钮
    is_exit_hover = exit_button.collidepoint(mouse_pos)
    if is_exit_hover:
        draw_glowing_rect(screen, (120, 40, 40), exit_button, glow_size=2)
        exit_text_color = WHITE
    else:
        draw_gradient_rect(screen, (80, 30, 30), (60, 20, 20), exit_button)
        exit_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (160, 60, 60), exit_button, 2, border_radius=8)
    exit_text = button_font.render("退出游戏", True, exit_text_color)
    exit_text_rect = exit_text.get_rect(center=exit_button.center)
    screen.blit(exit_text, exit_text_rect)
    
    # 移除pygame.display.flip()调用，避免在MOUSEMOTION事件中重复刷新屏幕
    # pygame.display.flip()
    return continue_button, rules_button, exit_button

def draw_rules_screen(screen, total_width, screen_height, scroll_offset=0):
    """绘制游戏规则界面"""
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 36, bold=True)
    subtitle_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20, bold=True)
    content_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 18)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20)
    
    # 绘制背景
    draw_gradient_rect(screen, BG_COLOR, (0, 0, 0), 
                       pygame.Rect(0, 0, total_width, screen_height))
    
    # 绘制标题
    title_text = title_font.render("游戏规则", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(total_width // 2, 60))
    screen.blit(title_text, title_rect)
    
    # 返回按钮
    back_button = pygame.Rect(30, 30, 80, 35)
    is_hover = back_button.collidepoint(pygame.mouse.get_pos())
    
    if is_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, back_button, glow_size=2)
        text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 30, 50), back_button)
        text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, back_button, 2, border_radius=6)
    back_text = button_font.render("返回", True, text_color)
    back_text_rect = back_text.get_rect(center=back_button.center)
    screen.blit(back_text, back_text_rect)
    
    # 扩大内容区域，减少边距
    content_area_x = 40  # 减少左边距
    content_area_y = 120
    content_area_width = total_width - 120  # 增加内容区域宽度，减少滚动条空间
    content_area_height = screen_height - 160  # 增加内容区域高度，减少上下边距
    
    # 创建内容区域的裁剪表面
    content_surface = pygame.Surface((content_area_width, content_area_height))
    content_surface.fill(BG_COLOR)
    
    # 游戏规则内容（扩展更多内容以测试滚动）
    rules_content = [
        ("游戏目标", "消除完整的横行来获得分数，挑战更高的等级和分数记录"),
        ("基础目标", "通过移动和旋转方块，消除完整的横行"),
        ("进阶目标", "挑战更高的等级，体验更快的游戏速度"),
        ("终极目标", "获得更高的分数，创造个人最佳记录"),
        ("挑战目标", "尝试消除多行，获得连击奖励"),
        ("", ""),
        ("操作说明", "使用键盘控制方块的移动、旋转和下落"),
        ("← →", "左右移动方块，调整方块位置"),
        ("↓", "加速下落，每格获得1分奖励"),
        ("↑", "旋转方块，改变方块朝向"),
        ("空格", "立即下落到底部，每格获得2分奖励"),
        ("P", "暂停/继续游戏，随时暂停休息"),
        ("ESC", "返回主菜单或调出游戏内菜单"),
        ("R", "重新开始游戏，重置所有数据"),
        ("", ""),
        ("计分规则", "根据消除行数和操作方式计算分数"),
        ("消除1行", "100 × 等级，基础消除奖励"),
        ("消除2行", "300 × 等级，双倍消除奖励"),
        ("消除3行", "500 × 等级，三倍消除奖励"),
        ("消除4行", "800 × 等级，四倍消除奖励"),
        ("软降得分", "每格1分，按住下键加速下落"),
        ("硬降得分", "每格2分，按空格键立即下落"),
        ("连击奖励", "连续消除行数越多，奖励越高"),
        ("", ""),
        ("等级系统", "每消除10行提升一个等级，速度会逐渐加快，挑战更高难度"),
        ("等级1", "速度：800ms/格，新手入门速度"),
        ("等级2", "速度：700ms/格，逐渐适应游戏节奏"),
        ("等级3", "速度：600ms/格，中等难度挑战"),
        ("等级4", "速度：500ms/格，需要快速反应"),
        ("等级5", "速度：400ms/格，高手级别速度"),
        ("等级6", "速度：350ms/格，极速挑战开始"),
        ("等级7", "速度：300ms/格，需要精准操作"),
        ("等级8", "速度：250ms/格，极限速度挑战"),
        ("等级9", "速度：200ms/格，大师级别难度"),
        ("等级10", "速度：150ms/格，终极挑战速度"),
        ("", ""),
        ("游戏结束", "当方块堆到顶部时游戏结束，挑战你的最高分数"),
        ("结束条件", "当方块堆叠到游戏区域顶部时游戏结束"),
        ("结束提示", "游戏结束时会显示最终分数和等级"),
        ("重新开始", "按R键可以立即重新开始游戏"),
        ("成绩记录", "游戏会记录你的最高分数和等级"),
        ("挑战自我", "每次游戏都是挑战自我的机会"),
        ("", ""),
        ("游戏技巧", "掌握这些技巧，提升你的游戏水平"),
        ("1", "优先消除底部的行，保持游戏区域整洁"),
        ("2", "保持游戏区域整洁，避免出现空洞"),
        ("3", "合理使用硬降功能，快速定位方块"),
        ("4", "注意下一个方块形状，提前规划布局"),
        ("5", "练习快速旋转操作，提高反应速度"),
        ("6", "学会使用I型方块消除多行"),
        ("7", "保持冷静，不要被高速吓倒"),
        ("8", "多练习，熟能生巧")
    ]
    
    def render_wrapped_text(surface, text, font, color, rect, line_spacing=5):
        """渲染自动换行的文本"""
        words = text.split()
        lines = []
        current_line = []
        
        for word in words:
            test_line = ' '.join(current_line + [word])
            test_surface = font.render(test_line, True, color)
            test_width = test_surface.get_width()
            
            if test_width <= rect.width:
                current_line.append(word)
            else:
                if current_line:
                    lines.append(' '.join(current_line))
                    current_line = [word]
                else:
                    # 单个词太长，强制换行
                    lines.append(word)
        
        if current_line:
            lines.append(' '.join(current_line))
        
        y = rect.y
        for line in lines:
            if y + font.get_height() <= rect.bottom:
                text_surface = font.render(line, True, color)
                surface.blit(text_surface, (rect.x, y))
                y += font.get_height() + line_spacing
        
        return len(lines) * (font.get_height() + line_spacing) - line_spacing
    
    # 计算内容总高度
    content_height = 0
    for title, content in rules_content:
        if title == "" and content == "":
            content_height += 20  # 空行
        elif title in ["游戏目标", "操作说明", "计分规则", "等级系统", "游戏结束", "游戏技巧"]:
            content_height += 35  # 标题
        else:
            # 计算内容文本的高度
            if content:
                full_text = f"{title}: {content}"
            else:
                full_text = title
            
            # 估算文本高度（考虑换行）
            text_rect = pygame.Rect(0, 0, content_area_width - 40, 1000)  # 留出左右边距
            estimated_height = render_wrapped_text(
                pygame.Surface((1, 1)), full_text, content_font, TEXT_COLOR, text_rect
            )
            content_height += max(25, estimated_height)  # 至少25像素高度
    
    # 绘制内容到内容表面
    y_pos = -scroll_offset  # 应用滚动偏移
    for title, content in rules_content:
        if title == "" and content == "":
            y_pos += 20  # 空行
            continue
        
        # 只绘制在可视区域内的内容
        if y_pos + 25 > 0 and y_pos < content_area_height:
            if title in ["游戏目标", "操作说明", "计分规则", "等级系统", "游戏结束", "游戏技巧"]:
                # 标题
                text = subtitle_font.render(title, True, NEON_BLUE)
                content_surface.blit(text, (0, y_pos))
                y_pos += 35
            else:
                # 内容 - 使用自动换行
                if content:
                    full_text = f"{title}: {content}"
                else:
                    full_text = title
                
                text_rect = pygame.Rect(20, y_pos, content_area_width - 40, content_area_height - y_pos)
                text_height = render_wrapped_text(content_surface, full_text, content_font, TEXT_COLOR, text_rect)
                y_pos += max(25, text_height)
        else:
            # 跳过不可见的内容，但更新位置
            if title in ["游戏目标", "操作说明", "计分规则", "等级系统", "游戏结束", "游戏技巧"]:
                y_pos += 35
            else:
                # 估算内容高度
                if content:
                    full_text = f"{title}: {content}"
                else:
                    full_text = title
                
                text_rect = pygame.Rect(0, 0, content_area_width - 40, 1000)
                estimated_height = render_wrapped_text(
                    pygame.Surface((1, 1)), full_text, content_font, TEXT_COLOR, text_rect
                )
                y_pos += max(25, estimated_height)
    
    # 将内容表面绘制到主屏幕
    screen.blit(content_surface, (content_area_x, content_area_y))
    
    # 绘制滚动条（如果内容超出可视区域）
    if content_height > content_area_height:
        scrollbar_width = 12
        scrollbar_x = total_width - 40
        scrollbar_y = content_area_y
        
        # 滚动条背景
        scrollbar_bg = pygame.Rect(scrollbar_x, scrollbar_y, scrollbar_width, content_area_height)
        pygame.draw.rect(screen, (50, 50, 70), scrollbar_bg, border_radius=6)
        
        # 计算滚动条滑块
        scroll_ratio = scroll_offset / max(1, content_height - content_area_height)
        slider_height = max(30, int(content_area_height * (content_area_height / content_height)))
        slider_y = scrollbar_y + int(scroll_ratio * (content_area_height - slider_height))
        
        # 滚动条滑块
        slider_rect = pygame.Rect(scrollbar_x, slider_y, scrollbar_width, slider_height)
        pygame.draw.rect(screen, NEON_BLUE, slider_rect, border_radius=6)
        
        # 滚动条边框
        pygame.draw.rect(screen, BUTTON_BORDER_COLOR, scrollbar_bg, 1, border_radius=6)
    
    # 移除pygame.display.flip()调用，避免在MOUSEMOTION事件中重复刷新屏幕
    # pygame.display.flip()
    return back_button, content_height, content_area_height

# 以下是独立运行时的代码，主游戏不会使用
if __name__ == "__main__":
    # 初始化pygame
    pygame.init()
    
    # 创建窗口
    screen = pygame.display.set_mode((TOTAL_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("俄罗斯方块 - 主菜单")
    
    # 显示初始化菜单
    menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
    
    running = True
    showing_rules = False
    showing_exit_confirm = False
    scroll_offset = 0
    content_height = 0
    content_area_height = 0
    dragging_scrollbar = False  # 滚动条拖拽状态
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 只处理鼠标左键点击
                if event.button == 1:  # 左键
                    if showing_exit_confirm:
                        # 在退出确认界面
                        yes_button, no_button = draw_exit_confirm_dialog(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                        if yes_button.collidepoint(event.pos):
                            running = False
                        elif no_button.collidepoint(event.pos):
                            showing_exit_confirm = False
                            menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                    elif showing_rules:
                        # 在规则界面，检查是否点击了返回按钮或滚动条
                        back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
                        if back_button.collidepoint(event.pos):
                            showing_rules = False
                            scroll_offset = 0
                            menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                        else:
                            # 检查是否点击了滚动条
                            scrollbar_width = 12
                            scrollbar_x = TOTAL_WIDTH - 40
                            scrollbar_y = 120
                            content_area_height = SCREEN_HEIGHT - 180
                            
                            if content_height > content_area_height:
                                scrollbar_rect = pygame.Rect(scrollbar_x, scrollbar_y, scrollbar_width, content_area_height)
                                if scrollbar_rect.collidepoint(event.pos):
                                    # 开始拖拽滚动条
                                    dragging_scrollbar = True
                                    scroll_ratio = (event.pos[1] - scrollbar_y) / content_area_height
                                    scroll_ratio = max(0, min(1, scroll_ratio))  # 限制在0-1范围内
                                    scroll_offset = int(scroll_ratio * max(0, content_height - content_area_height))
                    else:
                        # 在主菜单，检查菜单按钮
                        result = handle_menu_click(event.pos, menu_buttons)
                        if result == "start":
                            print("开始游戏")
                            running = False
                        elif result == "rules":
                            showing_rules = True
                            back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
                        elif result == "exit":
                            showing_exit_confirm = True
                            draw_exit_confirm_dialog(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
            elif event.type == pygame.MOUSEBUTTONUP:
                # 停止拖拽滚动条
                if event.button == 1:  # 左键释放
                    dragging_scrollbar = False
            elif event.type == pygame.MOUSEWHEEL and showing_rules:
                # 在规则界面处理滚轮事件
                scroll_offset -= event.y * 30  # 滚轮滚动速度
                scroll_offset = max(0, min(scroll_offset, max(0, content_height - content_area_height)))
                back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
            elif event.type == pygame.MOUSEMOTION:
                if showing_rules and dragging_scrollbar:
                    # 拖拽滚动条
                    scrollbar_width = 12
                    scrollbar_x = TOTAL_WIDTH - 40
                    scrollbar_y = 120
                    content_area_height = SCREEN_HEIGHT - 180
                    
                    if content_height > content_area_height:
                        # 计算新的滚动位置
                        mouse_y = event.pos[1]
                        scroll_ratio = (mouse_y - scrollbar_y) / content_area_height
                        scroll_ratio = max(0, min(1, scroll_ratio))  # 限制在0-1范围内
                        scroll_offset = int(scroll_ratio * max(0, content_height - content_area_height))
                        back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
                elif showing_exit_confirm:
                    # 更新退出确认对话框的悬停效果
                    draw_exit_confirm_dialog(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                elif not showing_rules:
                    # 重新绘制菜单以更新悬停效果
                    menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
    
    pygame.quit()
    sys.exit()
